package cn.chenhuanming.shh.administer.intermediary.business.eventHandler;

import cn.chenhuanming.shh.administer.entity.jpa.District;
import cn.chenhuanming.shh.administer.entity.jpa.Estate;
import cn.chenhuanming.shh.administer.exception.ResourceExistedException;
import cn.chenhuanming.shh.administer.repository.DistrictRepository;
import cn.chenhuanming.shh.administer.repository.EstateRepository;
import cn.chenhuanming.shh.administer.repository.UserSystemRepository;
import cn.chenhuanming.shh.administer.utils.AuthorityTool;
import cn.chenhuanming.shh.administer.utils.DistrictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Created by chenhuanming on 2017-07-31.
 *
 * @author chenhuanming
 */
@Component
@RepositoryEventHandler
public class EstateEventHandler {

    @Autowired
    DistrictRepository districtRepository;

    @Autowired
    EstateRepository estateRepository;

    @Autowired
    UserSystemRepository userSystemRepository;

    @HandleBeforeCreate
    public void beforeCreate(Estate estate){

        //检查名字是否存在
        Estate estate1 = new Estate();
        estate1.setName(estate.getName());
        estate1.setStatus("正常");
        if(estateRepository.findOne(Example.of(estate1))!=null)
            throw new ResourceExistedException("楼盘名字重复！");

        //片区检查
        District district = estate.getDistrict();
        DistrictUtils.isArea(district);
        estate.setCityName(district.getParent().getName());
        estate.setCityAreaName(district.getName());

        //创建时间等设置
        estate.setCreateTime(LocalDateTime.now());
        estate.setCreator(userSystemRepository.findOne(AuthorityTool.getPrincipal()));
        estate.setStatus("正常");
    }
}
